<?php

namespace yak\layui\models\rbac;

use Yii;
use yak\layui\helper\RbacHelper;
use yii\base\Model;
use yii\db\Exception;

/**
 * Class AssignForm
 * @package yak\layui\models\rbac
 */
class AssignForm extends Model
{

    public $permissions = [];
    public $roles = [];

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['roles', 'permissions'], 'safe'],
            [['roles', 'permissions'], 'filter', 'filter' => function ($value) {
                return empty($value) ? [] : $value;
            }],
        ];
    }

    public function setChildrenToRole($name)
    {
        $role = RbacHelper::getRole($name);
        if ($role instanceof \yii\rbac\Role && $this->validate()) {
            $trans = \Yii::$app->db->beginTransaction();
            try {
                RbacHelper::setChildrenToRole($role, $this->permissions, $this->roles);
                $trans->commit();
                return true;
            } catch (Exception $e) {
                $trans->rollBack();
                Yii::$app->session->setFlash('danger', $e->getMessage());
            }
        }
        return false;
    }

    public function setChildrenToUser($userId)
    {
        if ($this->validate()) {
            $trans = \Yii::$app->db->beginTransaction();
            try {
                RbacHelper::assign($userId, $this->permissions, $this->roles);
                $trans->commit();
                return true;
            } catch (Exception $e) {
                $trans->rollBack();
                Yii::$app->session->setFlash('danger', $e->getMessage());
            }
        }
        return false;
    }

    public static function rolesTreeList($name = '')
    {
        $data = [];
        foreach (RbacHelper::roles() as $key => $value) {
            if ($name === $key) continue;
            $v = $key;
            list($e1, $e2) = explode('-', $v);
            if (!empty($e2)) {
                $ctrl = $e1;
                $alias = $e1 . '_' . $e2;
            } else {
                $ctrl = 0;
                $alias = $e1;
            }
            $data[] = ['id' => $key, 'name' => $value, 'alias' => $alias, 'palias' => $ctrl];
        }
        return $data;
    }

    public static function permissionsLayuiTreeList()
    {
        $data = [];
        foreach (RbacHelper::permissions() as $key => $value) {
            $v = trim($key, '/');
            list($e1, $e2, $e3) = explode('/', $v);
            if (!empty($e3)) {
                $ctrl = $e3 === '*' ? 0 : $e1 . '_' . $e2 . '_*';
                $alias = $e1 . '_' . $e2 . '_' . $e3;
            } else {
                $ctrl = $e2 === '*' ? 0 : $e1 . '_*';
                $alias = $e1 . '_' . $e2;
            }
            $data[] = ['id' => $key, 'name' => $value, 'alias' => $alias, 'palias' => $ctrl];
        }

        // var_dump($data);die;
        return $data;
    }

}